{% extends 'base.html' %}
{% load static %}

{% block title %}资产管理 - 固定资产管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="{% url 'assets:index' %}">首页</a></li>
                <li class="breadcrumb-item active" aria-current="page">资产管理</li>
            </ol>
        </nav>
        
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2><i class="fas fa-boxes me-2"></i>资产管理</h2>
            <div class="btn-group">
                <a href="{% url 'assets:asset_create' %}" class="btn btn-primary">
                    <i class="fas fa-plus me-1"></i>新增资产
                </a>
                <button type="button" class="btn btn-outline-primary dropdown-toggle dropdown-toggle-split" data-bs-toggle="dropdown">
                    <span class="visually-hidden">更多操作</span>
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="{% url 'assets:bulk_import_assets' %}">
                        <i class="fas fa-upload me-2"></i>批量导入
                    </a></li>
                    <li><hr class="dropdown-divider"></li>
                    <li><a class="dropdown-item text-warning" href="#" onclick="batchUpdateStatus()">
                        <i class="fas fa-edit me-2"></i>批量更新状态
                    </a></li>
                    <li><a class="dropdown-item text-danger" href="#" onclick="batchDeleteAssets()">
                        <i class="fas fa-trash me-2"></i>批量删除
                    </a></li>
                </ul>
            </div>
        </div>
        
        <!-- 搜索和筛选 -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="get" class="row g-3">
                    <div class="col-md-4">
                        <div class="input-group">
                            <input type="text" class="form-control" name="search" placeholder="搜索资产名称或编号..." value="{{ search_query }}">
                            <button class="btn btn-outline-secondary" type="submit">
                                <i class="fas fa-search me-1"></i>搜索
                            </button>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="category" onchange="this.form.submit()">
                            <option value="">全部类别</option>
                            {% for category in categories %}
                                <option value="{{ category.id }}" {% if request.GET.category == category.id|stringformat:"s" %}selected{% endif %}>
                                    {{ category.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="status" onchange="this.form.submit()">
                            <option value="">全部状态</option>
                            <option value="available" {% if request.GET.status == 'available' %}selected{% endif %}>可用</option>
                            <option value="in_use" {% if request.GET.status == 'in_use' %}selected{% endif %}>使用中</option>
                            <option value="maintenance" {% if request.GET.status == 'maintenance' %}selected{% endif %}>维修中</option>
                            <option value="scrapped" {% if request.GET.status == 'scrapped' %}selected{% endif %}>已报废</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="department" onchange="this.form.submit()">
                            <option value="">全部部门</option>
                            {% for department in departments %}
                                <option value="{{ department.id }}" {% if request.GET.department == department.id|stringformat:"s" %}selected{% endif %}>
                                    {{ department.name }}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-outline-info w-100" onclick="clearSearch()">
                            <i class="fas fa-times me-1"></i>清除筛选
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 资产列表 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list me-2"></i>资产列表
                    {% if page_obj %}
                        <span class="badge bg-secondary ms-2">{{ page_obj.paginator.count }} 个资产</span>
                    {% endif %}
                </h5>
                <div class="d-flex align-items-center gap-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="selectAll" onchange="toggleSelectAll()">
                        <label class="form-check-label" for="selectAll">全选</label>
                    </div>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary active" onclick="switchView('table')">
                            <i class="fas fa-table"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="switchView('card')">
                            <i class="fas fa-th-large"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <form id="batchActionForm" method="post">
                    {% csrf_token %}
                    
                    <!-- 表格视图 -->
                    <div id="tableView" class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead class="table-dark">
                                <tr>
                                    <th width="5%">
                                        <input type="checkbox" class="form-check-input" id="selectAllHeader" onchange="toggleSelectAll()">
                                    </th>
                                    <th width="15%">资产名称</th>
                                    <th width="12%">资产编号</th>
                                    <th width="10%">类别</th>
                                    <th width="10%">状态</th>
                                    <th width="12%">所属部门</th>
                                    <th width="10%">采购价格</th>
                                    <th width="12%">启用日期</th>
                                    <th width="14%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for asset in page_obj %}
                                <tr>
                                    <td>
                                        <input type="checkbox" class="form-check-input asset-checkbox" name="asset_ids" value="{{ asset.pk }}">
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-box me-2 text-primary"></i>
                                            <div>
                                                <strong>{{ asset.name }}</strong>
                                                {% if asset.description %}
                                                    <br><small class="text-muted">{{ asset.description|truncatechars:30 }}</small>
                                                {% endif %}
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge bg-info">{{ asset.asset_number }}</span>
                                    </td>
                                    <td>
                                        {% if asset.category %}
                                            <span class="badge bg-secondary">{{ asset.category.name }}</span>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if asset.status == 'available' %}
                                            <span class="badge bg-success">
                                                <i class="fas fa-check me-1"></i>可用
                                            </span>
                                        {% elif asset.status == 'in_use' %}
                                            <span class="badge bg-primary">
                                                <i class="fas fa-user me-1"></i>使用中
                                            </span>
                                        {% elif asset.status == 'maintenance' %}
                                            <span class="badge bg-warning">
                                                <i class="fas fa-wrench me-1"></i>维修中
                                            </span>
                                        {% elif asset.status == 'scrapped' %}
                                            <span class="badge bg-danger">
                                                <i class="fas fa-times me-1"></i>已报废
                                            </span>
                                        {% else %}
                                            <span class="badge bg-secondary">{{ asset.get_status_display }}</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if asset.department %}
                                            {{ asset.department.name }}
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if asset.purchase_price %}
                                            <span class="text-success fw-bold">¥{{ asset.purchase_price|floatformat:2 }}</span>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        {% if asset.purchase_date %}
                                            <div class="text-nowrap">
                                                <i class="fas fa-calendar me-1 text-muted"></i>
                                                {{ asset.purchase_date|date:"m-d" }}
                                            </div>
                                            <small class="text-muted">{{ asset.purchase_date|date:"Y" }}</small>
                                        {% else %}
                                            <span class="text-muted">-</span>
                                        {% endif %}
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <a href="{% url 'assets:asset_detail' asset.pk %}" class="btn btn-outline-info" title="查看详情">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="{% url 'assets:asset_update' asset.pk %}" class="btn btn-outline-primary" title="编辑">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <div class="btn-group btn-group-sm">
                                                <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" title="更多操作">
                                                    <i class="fas fa-ellipsis-h"></i>
                                                </button>
                                                <ul class="dropdown-menu">
                                                    <li><a class="dropdown-item" href="{% url 'assets:asset_allocate' asset.pk %}">
                                                        <i class="fas fa-user-plus me-2"></i>分配
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="{% url 'assets:asset_transfer' asset.pk %}">
                                                        <i class="fas fa-exchange-alt me-2"></i>调拨
                                                    </a></li>
                                                    <li><a class="dropdown-item" href="{% url 'assets:asset_maintenance' asset.pk %}">
                                                        <i class="fas fa-wrench me-2"></i>维修
                                                    </a></li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <li><a class="dropdown-item text-danger" href="{% url 'assets:asset_delete' asset.pk %}" onclick="return confirm('确定要删除资产 {{ asset.name }} 吗？')">
                                                        <i class="fas fa-trash me-2"></i>删除
                                                    </a></li>
                                                </ul>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                                {% empty %}
                                <tr>
                                    <td colspan="9" class="text-center py-4">
                                        <div class="text-muted">
                                            <i class="fas fa-boxes fa-2x mb-2"></i>
                                            <p class="mb-0">暂无资产数据</p>
                                        </div>
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 卡片视图 -->
                    <div id="cardView" class="row" style="display: none;">
                        {% for asset in page_obj %}
                        <div class="col-md-6 col-lg-4 mb-3">
                            <div class="card h-100">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-start mb-2">
                                        <input type="checkbox" class="form-check-input asset-checkbox" name="asset_ids" value="{{ asset.pk }}">
                                        {% if asset.status == 'available' %}
                                            <span class="badge bg-success">可用</span>
                                        {% elif asset.status == 'in_use' %}
                                            <span class="badge bg-primary">使用中</span>
                                        {% elif asset.status == 'maintenance' %}
                                            <span class="badge bg-warning">维修中</span>
                                        {% elif asset.status == 'scrapped' %}
                                            <span class="badge bg-danger">已报废</span>
                                        {% endif %}
                                    </div>
                                    <h6 class="card-title">{{ asset.name }}</h6>
                                    <p class="card-text text-muted small">{{ asset.asset_number }}</p>
                                    <div class="mb-2">
                                        <small class="text-muted">类别：</small>
                                        <span class="badge bg-secondary">{{ asset.category.name|default:"-" }}</span>
                                    </div>
                                    <div class="mb-2">
                                        <small class="text-muted">部门：</small>
                                        {{ asset.department.name|default:"-" }}
                                    </div>
                                    {% if asset.purchase_price %}
                                    <div class="mb-2">
                                        <small class="text-muted">价格：</small>
                                        <span class="text-success fw-bold">¥{{ asset.purchase_price|floatformat:2 }}</span>
                                    </div>
                                    {% endif %}
                                    <div class="d-flex justify-content-between">
                                        <a href="{% url 'assets:asset_detail' asset.pk %}" class="btn btn-sm btn-outline-info">详情</a>
                                        <a href="{% url 'assets:asset_update' asset.pk %}" class="btn btn-sm btn-outline-primary">编辑</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {% empty %}
                        <div class="col-12 text-center py-4">
                            <div class="text-muted">
                                <i class="fas fa-boxes fa-2x mb-2"></i>
                                <p class="mb-0">暂无资产数据</p>
                            </div>
                        </div>
                        {% endfor %}
                    </div>
                </form>
            </div>
        </div>

        <!-- 分页 -->
        {% if page_obj.has_other_pages %}
        <nav aria-label="页面导航" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.department %}&department={{ request.GET.department }}{% endif %}">
                            <i class="fas fa-chevron-left"></i>
                        </a>
                    </li>
                {% endif %}
                
                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                        <li class="page-item active">
                            <span class="page-link">{{ num }}</span>
                        </li>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                        <li class="page-item">
                            <a class="page-link" href="?page={{ num }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.department %}&department={{ request.GET.department }}{% endif %}">{{ num }}</a>
                        </li>
                    {% endif %}
                {% endfor %}
                
                {% if page_obj.has_next %}
                    <li class="page-item">
                        <a class="page-link" href="?page={{ page_obj.next_page_number }}{% if search_query %}&search={{ search_query }}{% endif %}{% if request.GET.category %}&category={{ request.GET.category }}{% endif %}{% if request.GET.status %}&status={{ request.GET.status }}{% endif %}{% if request.GET.department %}&department={{ request.GET.department }}{% endif %}">
                            <i class="fas fa-chevron-right"></i>
                        </a>
                    </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>

<script>
function toggleSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll') || document.getElementById('selectAllHeader');
    const assetCheckboxes = document.querySelectorAll('.asset-checkbox');
    const isChecked = selectAllCheckbox.checked;
    
    assetCheckboxes.forEach(checkbox => {
        checkbox.checked = isChecked;
    });
    
    // 同步两个全选复选框的状态
    const selectAll = document.getElementById('selectAll');
    const selectAllHeader = document.getElementById('selectAllHeader');
    if (selectAll) selectAll.checked = isChecked;
    if (selectAllHeader) selectAllHeader.checked = isChecked;
}

function batchDeleteAssets() {
    const checkedBoxes = document.querySelectorAll('.asset-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        alert('请选择要删除的资产');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${checkedBoxes.length} 个资产吗？\n\n此操作不可撤销！`)) {
        const form = document.getElementById('batchActionForm');
        form.action = '{% url "assets:asset_batch_delete" %}';
        form.submit();
    }
}

function batchUpdateStatus() {
    const checkedBoxes = document.querySelectorAll('.asset-checkbox:checked');
    
    if (checkedBoxes.length === 0) {
        alert('请选择要更新状态的资产');
        return;
    }
    
    const status = prompt('请输入新状态（available/in_use/maintenance/scrapped）：');
    if (status && ['available', 'in_use', 'maintenance', 'scrapped'].includes(status)) {
        const form = document.getElementById('batchActionForm');
        const statusInput = document.createElement('input');
        statusInput.type = 'hidden';
        statusInput.name = 'new_status';
        statusInput.value = status;
        form.appendChild(statusInput);
        form.action = '{% url "assets:asset_batch_update_status" %}';
        form.submit();
    }
}

function switchView(viewType) {
    const tableView = document.getElementById('tableView');
    const cardView = document.getElementById('cardView');
    const buttons = document.querySelectorAll('.btn-group .btn');
    
    buttons.forEach(btn => btn.classList.remove('active'));
    
    if (viewType === 'table') {
        tableView.style.display = 'block';
        cardView.style.display = 'none';
        buttons[0].classList.add('active');
    } else {
        tableView.style.display = 'none';
        cardView.style.display = 'block';
        buttons[1].classList.add('active');
    }
}

function clearSearch() {
    window.location.href = '{% url "assets:asset_list" %}';
}

// 监听单个复选框变化，更新全选状态
document.addEventListener('DOMContentLoaded', function() {
    const assetCheckboxes = document.querySelectorAll('.asset-checkbox');
    const selectAll = document.getElementById('selectAll');
    const selectAllHeader = document.getElementById('selectAllHeader');
    
    assetCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const checkedCount = document.querySelectorAll('.asset-checkbox:checked').length;
            const totalCount = assetCheckboxes.length;
            
            if (selectAll) selectAll.checked = checkedCount === totalCount;
            if (selectAllHeader) selectAllHeader.checked = checkedCount === totalCount;
        });
    });
});
</script>
{% endblock %}